package com.derbysoft.nuke.kafka.manager.integration.kafka;

import com.google.common.collect.Lists;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KafkaConsumerStarter {

//    String bootstrapServers = "localhost:9091;localhost:9092;localhost:9093";
    String bootstrapServers = "localhost:9092";

    public void start() {
        Map<String, Object> conf = new HashMap<>();
        conf.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        conf.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        conf.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer-group-1");
        conf.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        conf.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(conf);
//        kafkaConsumer.subscribe(Lists.newArrayList("test"));
        TopicPartition topicPartition = new TopicPartition("test", 0);
        Set<TopicPartition> topicPartitions = Collections.singleton(topicPartition);
        kafkaConsumer.assign(topicPartitions);
//        kafkaConsumer.seekToBeginning(topicPartitions);
        kafkaConsumer.seek(topicPartition, 650L);
        while (true) {
            System.out.println("start to poll");
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(3000);
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(String.format("message of topic[%s], partition[%s], offset[%s], content[%s]", consumerRecord.topic(), consumerRecord.partition(), consumerRecord.offset(), consumerRecord.value()));
            }
        }

    }

    public static void main(String[] args) {
        KafkaConsumerStarter starter = new KafkaConsumerStarter();
        starter.start();
    }

}
